package com.jiulan.hearthearing.ui.home.index;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseVPFragment;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.course.activity.CourseDetailsArticleActivity;
import com.jiulan.hearthearing.ui.course.activity.CourseDetailsLuboActivity;
import com.jiulan.hearthearing.ui.heart.activity.ClassifyActivity;
import com.jiulan.hearthearing.ui.home.adapter.HomeMenuAdapter;
import com.jiulan.hearthearing.ui.home.adapter.HomeArticleAdapter;
import com.jiulan.hearthearing.ui.home.adapter.HomeCourseAdapter;
import com.jiulan.hearthearing.ui.home.adapter.HomeNewsAdapter;
import com.jiulan.hearthearing.ui.main.MainActivity;
import com.jiulan.hearthearing.ui.menus.MenuModel;
import com.jiulan.hearthearing.ui.home.model.HomeModel;
import com.jiulan.hearthearing.ui.news.activity.NewsActivity;
import com.jiulan.hearthearing.ui.news.activity.NewsDetailsActivity;
import com.jiulan.hearthearing.utils.ActivityUtils;
import com.jiulan.hearthearing.widget.SpaceVerticalItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shehuan.niv.NiceImageView;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 首页
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public class HomeIndex extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private HomeModel model;
    private HomeMenuAdapter homeMenuAdapter;
    private List<MenuModel> menuModels;
    private HomeCourseAdapter courseAdapter;
    private HomeArticleAdapter articleAdapter;
    private HomeNewsAdapter newsAdapter;

    private View view;
    private SmartRefreshLayout smartLayout;
    private NestedScrollView scrollView;
    private LinearLayout llSearch;
    private ImageView ivMsg;
    private XBanner banner;
    private RecyclerView rcvActive;
    private RecyclerView rcvKecheng;
    private RecyclerView rcvWenzhang;
    private RecyclerView rcvNews;
    private TextView tvCheckKecheng;
    private TextView tvCheckWenzhang;
    private TextView tvCheckUnion;
    private TextView tvCheckNews;
    private NiceImageView nivToTop;
    private ImageView ivLeftPic;
    private ImageView ivRightTopPic;
    private ImageView ivRightBottomPic;

    public static HomeIndex newInstance(String content) {
        Bundle arguments = new Bundle();
        arguments.putString("string", content);
        HomeIndex fl = new HomeIndex();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home_index, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    private void initView() {
        smartLayout = view.findViewById(R.id.smartLayout);
        scrollView = view.findViewById(R.id.scrollView);
        llSearch = view.findViewById(R.id.llSearch);
        ivMsg = view.findViewById(R.id.ivMsg);
        banner = view.findViewById(R.id.banner);
        rcvActive = view.findViewById(R.id.rcvActive);
        rcvKecheng = view.findViewById(R.id.rcvKecheng);
        rcvWenzhang = view.findViewById(R.id.rcvWenzhang);
        rcvNews = view.findViewById(R.id.rcvNews);
        nivToTop = view.findViewById(R.id.nivToTop);
        tvCheckKecheng = view.findViewById(R.id.tvCheckKecheng);
        tvCheckWenzhang = view.findViewById(R.id.tvCheckWenzhang);
        tvCheckUnion = view.findViewById(R.id.tvCheckUnion);
        tvCheckNews = view.findViewById(R.id.tvCheckNews);
        ivLeftPic = view.findViewById(R.id.ivLeftPic);
        ivRightTopPic = view.findViewById(R.id.ivRightTopPic);
        ivRightBottomPic = view.findViewById(R.id.ivRightBottomPic);
        llSearch.setOnClickListener(this);
        ivMsg.setOnClickListener(this);
        tvCheckKecheng.setOnClickListener(this);
        tvCheckWenzhang.setOnClickListener(this);
        tvCheckUnion.setOnClickListener(this);
        tvCheckNews.setOnClickListener(this);
        nivToTop.setOnClickListener(this);
        rcvActive.setLayoutManager(new GridLayoutManager(context, 5));
        rcvKecheng.setLayoutManager(new GridLayoutManager(context, 2));
        rcvWenzhang.setLayoutManager(new LinearLayoutManager(context));
        rcvWenzhang.addItemDecoration(new SpaceVerticalItemDecoration(context, R.dimen.dp_12));
        rcvNews.setLayoutManager(new LinearLayoutManager(context));
        rcvNews.addItemDecoration(new SpaceVerticalItemDecoration(context, R.dimen.dp_6));
        smartLayout.setEnableLoadMore(false);
        smartLayout.setEnableNestedScroll(true);
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getData(null);
                    }
                }, 1000);
            }
        });
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > oldScrollY) {//下滑
                    nivToTop.setVisibility(View.VISIBLE);
                }
                if (scrollY < oldScrollY) {//上滑

                }
                if (scrollY == 0) {//滑倒顶部
                    nivToTop.setVisibility(View.GONE);
                }
            }
        });
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onFragmentFirstVisible() {
        smartLayout.autoRefresh();
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {

    }

    private void getData(String loadingMsg) {
        HashMap hashMap = new HashMap();
        new HttpRequest(context).doGet(UrlConstants.home_index, loadingMsg, hashMap, HomeModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                smartLayout.finishRefresh();
                if (result instanceof HomeModel) {
                    model = (HomeModel) result;
                    setBanner();
                    setMenus();
                    setClass();
                    setArticle();
                    setUnion();
                    setNews();
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void setUnion() {
        if (!ActivityUtils.isDestroy((Activity) context)) {
            Glide.with(context).load(model.getData().getGuoyi().get(0).getPic()).into(ivLeftPic);
            Glide.with(context).load(model.getData().getGuoyi().get(1).getPic()).into(ivRightTopPic);
            Glide.with(context).load(model.getData().getGuoyi().get(2).getPic()).into(ivRightBottomPic);
        }
    }

    private void setNews() {
        newsAdapter = new HomeNewsAdapter(model.getData().getNews());
        rcvNews.setAdapter(newsAdapter);
        newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                NewsDetailsActivity.actionStart(context, model.getData().getNews().get(position).getId());
            }
        });
    }

    private void setArticle() {
        articleAdapter = new HomeArticleAdapter(model.getData().getBest_class_news());
        rcvWenzhang.setAdapter(articleAdapter);
        articleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CourseDetailsArticleActivity.actionStart(context, model.getData().getBest_class_news().get(position).getId());
            }
        });
    }

    private void setClass() {
        courseAdapter = new HomeCourseAdapter(model.getData().getBest_class());
        rcvKecheng.setAdapter(courseAdapter);
        courseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CourseDetailsLuboActivity.actionStart(context, model.getData().getBest_class().get(position).getId());
            }
        });
    }

    private void setMenus() {
        menuModels = new ArrayList<>();
        menuModels.add(new MenuModel(R.mipmap.home_icon_heart_translation, "心译通"));
        menuModels.add(new MenuModel(R.mipmap.home_icon_business_school, "商学院"));
        menuModels.add(new MenuModel(R.mipmap.home_icon_private_school, "私塾院"));
        menuModels.add(new MenuModel(R.mipmap.home_icon_e, "e世界"));
        menuModels.add(new MenuModel(R.mipmap.home_icon_music_bar, "音乐吧"));
        homeMenuAdapter = new HomeMenuAdapter(menuModels);
        rcvActive.setAdapter(homeMenuAdapter);
        homeMenuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (menuModels.get(position).getActiveName()) {
                    case "心译通":
                        Intent intent = new Intent(MainActivity.LOCAL_BROADCAST);
                        intent.putExtra("action", 1);
                        MainActivity.localBroadcastManager.sendBroadcast(intent);
                        break;
                    case "商学院":
                        Intent intent2 = new Intent(MainActivity.LOCAL_BROADCAST);
                        intent2.putExtra("action", 2);
                        MainActivity.localBroadcastManager.sendBroadcast(intent2);
                        break;
                    case "私塾院":
                        Toast.makeText(context, "私塾院", Toast.LENGTH_SHORT).show();
                        break;
                    case "e世界":
                        Toast.makeText(context, "e世界", Toast.LENGTH_SHORT).show();
                        break;
                    case "音乐吧":
                        Toast.makeText(context, "音乐吧", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    /**
     * banner
     */
    private void setBanner() {
        if (model.getData().getBanner().size() > 0) {
            banner.setVisibility(View.VISIBLE);
            banner.setBannerData(model.getData().getBanner());
            //设置广告图片点击事件
            banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                @Override
                public void onItemClick(XBanner banner, Object model, View view, int position) {
                    Toast.makeText(context, "点击了第" + (position + 1) + "图片", Toast.LENGTH_SHORT).show();
                }
            });
            //加载广告图片
            banner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object object, View view, int position) {
                    //在此处使用图片加载框架加载图片，demo中使用glide加载，可替换成自己项目中的图片加载框架
                    Glide.with(context).load(model.getData().getBanner().get(position).getXBannerUrl()).placeholder(R.mipmap.home_banner).error(R.mipmap.home_banner).into((ImageView) view);
                }
            });
        } else {
            banner.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llSearch://搜索
//                SearchActivity.actionStart(context);
                break;
            case R.id.ivMsg://消息
//                MsgActivity.actionStart(context);
                break;
            case R.id.tvCheckKecheng:
                ClassifyActivity.actionStart(context, 2);
                break;
            case R.id.tvCheckWenzhang:
                ClassifyActivity.actionStart(context, 3);
                break;
            case R.id.tvCheckUnion:
                break;
            case R.id.tvCheckNews:
                NewsActivity.actionStart(context);
//                NewsClassifyActivity.actionStart(context);
                break;
            case R.id.nivToTop:
                scrollView.fling(0);
                scrollView.smoothScrollTo(0, 0);
                break;
        }
    }
}
